package leetcode.code1743;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int[] restoreArray(int[][] adjacentPairs) {
		int len = adjacentPairs.length;
		int n = len + 1;
		Map<Integer, List<Integer>> links = new HashMap<>();
		for (int i = 0; i < adjacentPairs.length; i++) {
			int[] pair = adjacentPairs[i];
			int u = pair[0], v = pair[1];
			List<Integer> list1 = links.getOrDefault(u, new ArrayList<>());
			list1.add(v);
			links.put(u, list1);
			List<Integer> list2 = links.getOrDefault(v, new ArrayList<>());
			list2.add(u);
			links.put(v, list2);
		}
		int[] ans = new int[n];
		for (Map.Entry<Integer, List<Integer>> entry : links.entrySet()) {
			if (entry.getValue().size() == 1) {
				ans[0] = entry.getKey();
				break;
			}
		}
		for (int i = 1; i < n; i++) {
			List<Integer> list = links.get(ans[i - 1]);
			if (list.size() == 1) {
				ans[i] = list.get(0);
			} else if (list.get(0) == ans[i - 2]) {
				ans[i] = list.get(1);
			} else {
				ans[i] = list.get(0);
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(H.str2array3("[1,2,3,4]"), this.restoreArray(H.str2array1("[[2,1],[3,4],[3,2]]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		System.out.println(Integer.MAX_VALUE);
	}

}
